package com.hrz.datasync.kafka.producer;

import com.alibaba.fastjson.JSON;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @作  者: 侯建军
 * @日  期: 2018/11/05 10:33:19
 * @描  述: Kafka消息发送
 */
@Component
@Log
public class KafkaSender<T> {
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
     /**
     * kafka 发送消息
     *
     * @param obj 消息对象
     */
    public void send(T obj,String topic) {
        String jsonObj = JSON.toJSONString(obj);
        log.info("------------ 消息 = {}"+jsonObj);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, jsonObj);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("生产: 消息发送失败:" + throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //业务处理
                log.info("消息发送成功:");
                log.info("生产消息结果: " + stringObjectSendResult.toString());
            }
        });
    }
}